<!--
 * @Author: yeminglong
 * @Date: 2023-11-21 10:01:51
 * @LastEditTime: 2023-11-21 13:58:40
 * @LastEditors: yeminglong
 * @Description:
-->
<template>
  <el-form
    :model="formModel1"
    status-icon
    :rules="rules1"
    ref="ruleForm1"
    label-width="0"
    label-suffix="："
    class="login-form-element"
  >
    <el-form-item prop="username">
      <el-input
        clearable
        v-model="formModel1.username"
        placeholder="请输入账号"
        autocomplete="off"
        size="large"
        prefix-icon="el-icon-user"
        v-on:keyup.native.13="submitLogin"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        clearable
        type="password"
        v-model="formModel1.password"
        :show-password="true"
        autocomplete="off"
        size="large"
        prefix-icon="el-icon-lock"
        placeholder="请输入密码"
        v-on:keyup.native.13="submitLogin"
      ></el-input>
    </el-form-item>
    <el-form-item prop="code" v-if="captchaCode.captchaEnabled">
      <div style="display: flex; ">
        <div>
          <el-input
            clearable
            v-model="formModel1.code"
            placeholder="请输入验证码"
            autocomplete="off"
            size="large"
            prefix-icon="el-icon-mouse"
            v-on:keyup.native.13="submitLogin"
            maxlength="4"
            style="width: 200px"
          ></el-input>
        </div>
        <div style="display: flex; align-items: center">
          <span v-if="captchaCode.isLoading">
            验证码正在加载...
            <i class="el-icon-loading"></i>
          </span>
          <img
            @click="fetchCaptchaCode"
            title="点击我刷新验证码"
            v-else
            style="object-fit: contain; border-radius: 4px;height: 40px;margin-left: 10px;cursor:pointer;"
            :src="`data:image/gif;base64,${captchaCode.img}`"
            alt=""
          />
        </div>
      </div>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" class="login-button" @click="submitLogin" :loading="isLoading">
        <span class="button-text">登录</span>
      </el-button>
    </el-form-item>
    <el-form-item>
      <div class="sub-login">
        <el-link type="primary" :underline="false" :href="authenticationUrl">统一认证登陆</el-link>
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
import { flattenTree, isDev } from '@/utils/index.js'
import { mapActions, mapGetters } from 'vuex'
import LoginServiceApi from '@/views/auth/login/assets/loginServiceApi'
import { setToken } from '@/token'
export default {
  name: 'LoginForm',
  computed: {
    authenticationUrl() {
      return window.__CTC_ENV__.VUE_APP_AUTHENTICATION_URL
    }
  },
  data() {
    const createModel = () => {
      let ret = {
        username: '',
        password: '',
        code: ''
      }

      if (isDev) {
        ret = {
          username: 'huangjiaxuan',
          password: 'Jointsky123.com',
          code: ''
        }
      }

      return ret
    }
    return {
      isLoading: false,
      formModel1: createModel(),
      captchaCode: {
        isLoading: false,
        captchaEnabled: false,
        img: '',
        uuid: ''
      },
      rules1: {
        username: {
          required: true,
          message: '请输入用户名',
          trigger: 'change'
          // validator(rule, value, callback) {
          // 	if (isEmpty(value)) {
          // 		callback(new Error('请输入账号'))
          // 	} else {
          // 		if (/^1[34578]\d{9}$/.test(value) == false) {
          // 			callback(new Error('请输入正确的手机号'))
          // 		} else {
          // 			callback()
          // 		}
          // 	}
          // }
        },
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{6,20}$/
              if (value.length < 6 || value.length > 20) {
                callback(new Error('密码长度必须介于 6 和 20 之间'))
              } else if (reg.test(value) === false) {
                callback(new Error('密码包含大小写字母、数字和特殊字符'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // ...mapActions('loginStore', {
    //   fetchUserInfo: 'fetchUserInfo'
    // }),
    ...mapActions('loginStore', ['doLogin', 'fetchUserInfo']),
    // 获取验证码
    async fetchCaptchaCode() {
      this.formModel1.code = ''
      this.captchaCode.isLoading = true
      try {
        const { captchaEnabled, img, uuid } = await LoginServiceApi.authCaptchaCode()
        Object.assign(this.captchaCode, { captchaEnabled, img, uuid })
      } catch (e) {
        Object.assign(this.captchaCode, {
          captchaEnabled: false,
          img: '',
          uuid: ''
        })
      } finally {
        this.captchaCode.isLoading = false
      }
    },
    submitLogin() {
      this.$refs.ruleForm1.validate(async valid => {
        if (valid) {
          try {
            if (isDev) {
              setToken('test123456')
              this.$router.push({
                name: 'Welcome'
              })
              return
            }

            const { uuid } = this.captchaCode
            this.isLoading = true
            // 短信登录
            const loginParams = {
              ...this.formModel1,
              uuid
            }
            await this.doLogin(loginParams)
            const [userInfo, routers] = await this.fetchUserInfo()
            console.log(userInfo, routers)
            // const { userInfo, routers } = await this.fetchUserInfo()
            const defaultUrl = flattenTree(routers).filter(v => v.query && v.query === 'menu')[0]?.path
            if (defaultUrl) {
              this.$router.push(defaultUrl)
            } else {
              this.$router.push({
                name: 'Welcome'
              })
            }
          } catch (e) {
            this.fetchCaptchaCode()
            console.log(e)
          } finally {
            this.isLoading = false
          }
        }
      })
    }
  },
  mounted() {
    this.fetchCaptchaCode()
  }
}
</script>

<style scoped lang="scss">
.login-form-element {
  :deep(.el-form-item__error) {
    color: #ff2525;
  }

  :deep(.el-input__inner) {
    color: #ffff;
    line-height: 42px;
    height: 42px;
    background: rgba(119, 189, 223, 0.91);
    border: 1px solid #3f9ad1;
    box-shadow: rgba(242, 242, 242, 0.35) 0px 0px 4px 0px, rgba(202, 202, 202, 0.76) 0px 1px 1px 0px inset;
  }
}

.login-button {
  margin-top: 10px;
  width: 100%;
  cursor: pointer;

  .button-text {
    // font-weight: bolder;
    font-size: 16px;
    color: #ffff;
    font-weight: bolder;
    cursor: pointer;
  }
}

.sub-login {
  display: flex;
  justify-content: flex-end;

  .el-link {
    font-size: 16px;
    color: #ffff;
  }
}
</style>
